//
//  ErrorTracker.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/8.
//

import Foundation
import Foundation
import RxSwift
import RxCocoa

final class ErrorTracker: SharedSequenceConvertibleType {
    typealias SharingStrategy = DriverSharingStrategy
    private let subject = PublishSubject<Error>()
    
    func trackError<O: ObservableConvertibleType>(_ source: O) -> Observable<O.Element> {
        return source.asObservable().do(onError: onError)
    }
    
    func asSharedSequence() -> SharedSequence<DriverSharingStrategy, Error> {
        return subject.asDriver(onErrorDriveWith: .empty())
    }
    
    func asObservable() -> Observable<Error> {
        return subject.asObservable()
    }
    
    private func onError(_ error: Error) {
        subject.onNext(error)
    }
    
    deinit {
        subject.onCompleted()
    }
}

extension ObservableConvertibleType {
    func trackError(_ tracker: ErrorTracker) -> Observable<Element> {
        return tracker.trackError(self)
    }
}
